﻿/*
 * Upload Image Crop Plugin
 * 支持滚轴放大缩小，图片拖动位置(上传图片和裁切图片均通过后台程序处理)，不受浏览器限制
 * QQ:7103505
 *
 * @version 0.1
 */
; (function ($) {
    'use strict';
    $.fn.UploadImageCrop = function (options) {
        var opts = $.extend({}, $.fn.UploadImageCrop.defaults, options);

        function out() {
            var s = "";
            var numargs = arguments.length;
            for (var i = 0 ; i < numargs; i++) {
                s += i + ">：" + arguments[i] + ";";
            }
            if (console && console.log)
                console.log(s);
        }

        return (function (ths) {
            var $this = ths
                , option = $.meta ? $.extend({}, opts, $this.data()) : opts
                , image_target
                , W
                , H
                , BL
                , WIDTH
                , HEIGHT
                , BLX
                , PCENTER
                , startmousepoint
                , DROP;
                var $preview = $this.find(".preview")
                , pre_width = $preview.width()
                , pre_height = $preview.height()
                , $img = $preview.find("img")
                , $fangda = $this.find(option.fangda)
                , $suoxiao = $this.find(option.suoxiao);


            //取适合的区间数据
            function GetTrueNumber(min, max, value) {
                return Math.max(min, Math.min(max, value));
            };

            function zoom(step) {
                var center = {
                    top: $img.position().top + $img.height() / 2,
                    left: $img.position().left + $img.width() / 2
                };
                BLX += step?step:0.1;
                BLX = GetTrueNumber(BL[0], BL[1], BLX);

                out(BLX);
                W = WIDTH * BLX;
                H = HEIGHT * BLX;

                cropimage(center.left - W / 2, center.top - H / 2);
            };

            //增加拖动事件
            function SetDrop() {
                $img.on("mousedown", function (e) {
                    e.preventDefault();
                    e.stopPropagation();

                    DROP = true;
                    startmousepoint = { w: e.pageX, h: e.pageY };
                    PCENTER = { left: $img.position().left, top: $img.position().top }
                });
                $img.on("mouseup", function (e) {
                    DROP = false;
                    startmousepoint = { w: e.pageX, h: e.pageY };
                });

                $img.on("mouseout", function (e) {
                    DROP = false;
                    startmousepoint = { w: e.pageX, h: e.pageY };
                });

                $img.on("mousemove", function (e) {
                    if (DROP)
                        move({ w: e.pageX, h: e.pageY });
                });
            }

            //移动对象
            function move(poi) {
                var _left = poi.w - startmousepoint.w;
                var _top = poi.h - startmousepoint.h;

                var top, left;
                top = GetTrueNumber(pre_height - H, 0, PCENTER.top + _top);
                left = GetTrueNumber(pre_width - W, 0, PCENTER.left + _left);

                cropimage(left, top);
            }

            function cropimage(left,top)
            {
                $img.stop().animate({
                    left: GetTrueNumber(pre_width-W,0, left),
                    top: GetTrueNumber(pre_height-H,0, top),
                    width: W,
                    height: H
                }, 50);
            }

            //设置背景，放大缩小的比例
            function setrange() {
                var blx = WIDTH / pre_width;
                var bly = HEIGHT / pre_height;

                if(blx > bly)
                {
                    BL = [1 / bly > 1 ? bly : (1 / bly), Math.max(1, 1 / bly)];
                    out("blx");
                }else
                {
                    BL = [1 / blx > 1 ? blx : (1 / blx), Math.max(1, 1 / blx)];
                    out("bly");
                }
                out(BL[0], BL[1]);
                //设置为最小比例
                BLX = (BL[0] + BL[1])/2;
            };

            function setwheel() {
                $this.find("div,img").mousewheel(function (event, delta, deltaX, deltaY) {
                    event.stopPropagation();

                    if (delta) {
                        zoom(0.1 * delta);
                    }
                    
                });
            }

            $this.find("input[type='file']").fileupload({
                url: option.url + "?flag=upload&t="+new Date(),
                //这里存在问题
                dataType: 'text',
                //autoUpload: true,
                maxNumberOfFiles: 1,
                done: function (e, data) {
                    var _data = eval("("+data.result+")");
                    loadImage(_data);
                },
                progressall: function (e, data) {
                    //var progress = parseInt(data.loaded / data.total * 100, 10);
                    //$('#progress .progress-bar').css(
                    //    'width',
                    //    progress + '%'
                    //);
                }
            });//.prop('disabled', true);

            function loadImage(data)
            {
                $img[0].src = data.link;

                WIDTH = data.width;
                HEIGHT = data.height;
                out(WIDTH, HEIGHT);
                setrange();

                W = WIDTH * BLX;
                H = HEIGHT * BLX;
                cropimage(-(W - pre_width) / 2, -(H - pre_height) / 2);

                SetDrop();
                setwheel();
                $fangda.click(function () { zoom(0.1) });
                $suoxiao.click(function () { zoom(-0.1) });
            }

            function getdata(fun)
            {
                if (!$img.attr("src") || $img.attr("src") == "")
                {
                    alert("没有数据!");
                    return null;
                }

                $.post(
                    option.url+"?flag=crop&t="+new Date(),
                    {
                        fileName: $img.attr("src"),
                        width: pre_width,
                        height: pre_height,
                        bili: BLX,
                        top: $img.position().top,
                        left:$img.position().left
                    },
                    function (data) {
                        var json = eval("(" + data + ")");

                        if ($(".show").length > 0)
                            $(".show").attr("src", json.link);

                        if (fun) fun(json);
                    });
            }

            return {
                zoom: zoom,
                data: getdata
            }
        })(this);
    };

    // default options
    $.fn.UploadImageCrop.defaults = {
        fangda: '.fangda',
        suoxiao: '.suoxiao',
        url:'upload.aspx',
        sfWheel: true
    };

})(jQuery);